package com.asialjim.wechat.apiservice.executor.handler;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: HttpResponseProxy ]</i></h2><strong>
 * <p> http response proxy
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/1   &nbsp;&nbsp; JDK 8
 */
@Data
public class HttpResponseProxy {
    private static final Pattern PATTERN = Pattern.compile(".*filename=\"(.*)\"");

    private CloseableHttpResponse apacheHttpResponse;

    public HttpResponseProxy(CloseableHttpResponse apacheHttpResponse) {
        this.apacheHttpResponse = apacheHttpResponse;
    }


    /**
     * <h3>METHOD DESCRIPTION <i>[ NAME: getFileName ]</i></h3>
     * get file name from http response
     * @return {@link String file name}
     * @author Asial Jim &nbsp;&nbsp;<span>Email:asialjim@hotmail.com &nbsp;&nbsp; asialjim@qq.com</span>
     * @since 2021/3/1 13:58
     */
    public String getFileName() {
        //由于对象只能由一个构造方法实现，因此三个response对象必定且只有一个不为空
        if (this.apacheHttpResponse != null) {
            return this.getFileName(this.apacheHttpResponse);
        }
        //cannot happen
        return null;
    }

    private String getFileName(CloseableHttpResponse response) {
        Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
        if (Objects.isNull(contentDispositionHeader) || contentDispositionHeader.length == 0){
            // TODO throw a exception
        }

        return this.extractFileNameFromContentString(contentDispositionHeader[0].getValue());
    }


    private String extractFileNameFromContentString(String content) {

        if (StringUtils.isBlank(content)){
            // TODO throw a exception
        }

        Matcher m = PATTERN.matcher(content);
        if (m.matches()) {
            return m.group(1);
        }

        // TODO throw a exception
        return null;
    }
}